<template>
  <li :class="{ complete: item.complete, editing: item === editedTodo }">
    <!-- 编辑框 -->
    <div class="view">
      <input type="checkbox" class="checkbox-border" v-model="item.complete" />
      <label @dblclick="editTodo(item)"> {{ item.title }} </label>
      <span class="removeIcon" @click="removeTodo(item)">×</span>
    </div>

    <!-- 修改输入框 -->
    <div class="edit">
      <EditTodo
        v-model="item.title"
        v-edit-fous="item === editedTodo"
        @blur="doneEdit(item)"
        @keyup.enter="doneEdit(item)"
        @keyup.escape="cacelTodo(item)"
      ></EditTodo>
    </div>
  </li>
</template>
<script>
import { reactive } from "vue";
export default {
  // 自定义指令
  directives: {
    "edit-fous": (el, { value }) => {
      if (value) {
        el.focus();
      }
    },
  },
  props: ["item", "editedTodo"],
  setup(props, { emit }) {
    const state = reactive({
      beforeCacelTodo: null,
    });
    // 删除待办
    function removeTodo(item) {
      emit("removeTodo", item);
    }
    // 双击修改todo
    function editTodo(todo) {
      // 缓存修改前todo
      state.beforeCacelTodo = todo.title;
      emit("update:editedTodo", todo);    
    }
    // 退出修改
    function cacelTodo(todo) {
      todo.title = state.beforeCacelTodo;
      emit("update:editedTodo", null);    
    }
    // 保存修改
    function doneEdit(todo) {
      // 清空当前编辑的todo
      emit("update:editedTodo", null);    
    }

    return{
        removeTodo,
        editTodo,
        cacelTodo,
        doneEdit
    }
  },
};
</script>


<style scoped>
li {
  list-style: none;
  display: flex;
  justify-content: center;
  align-items: center;
}
.removeIcon {
  margin-left: 20px;
  cursor: pointer;
  font-size: 30px;
  color: tomato;
}
.complete > label {
  text-decoration: line-through;
}
.edit,
.editing .view {
  display: none;
}

.view,
.editing .edit {
  display: block;
}
</style>